package com.zt.student.service.impl;

import com.zt.common.common.ApiException;
import com.zt.common.common.CodeMsg;
import com.zt.common.pojo.homework.Homework;
import com.zt.common.pojo.homework.HomeworkAnswer;
import com.zt.common.utils.JwtUtil;
import com.zt.student.dao.HomeworkAnswerDao;
import com.zt.student.service.HomeworkAnswerService;
import com.zt.student.service.HomeworkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * description:
 * author:zt
 * date:2022-02-13
 */
@Service
@Transactional
public class HomeworkAnswerServiceImpl implements HomeworkAnswerService {

    @Autowired
    private HomeworkAnswerDao homeworkAnswerDao;
    @Autowired
    private HomeworkService homeworkService;

    @Override
    public void insert(HomeworkAnswer homeworkAnswer, HttpServletRequest request) {
        Date date = new Date();
        Homework homework = homeworkService.getByHomeworkId(homeworkAnswer.getHomeworkId());
        //如果回答时间已经晚于截至时间则异常
        if (homework.getDeadline().before(date)) throw new ApiException(CodeMsg.DEADLINE_HAS_EXPIRED);

        String studentId = JwtUtil.decodedGetID(request.getHeader("Authorization"));

        homeworkAnswer.setStudentId(studentId).setAnswerTime(date);
        homeworkAnswerDao.insert(homeworkAnswer);
    }
}
